/**  
 * All rights Reserved, Designed By <a href="www.itttq.com" target="_blank">www.itttq.com</a>
 * @date:   2018-01-6 11:42:21
 * @Copyright: 2017 <a href="www.itttq.com" target="_blank">www.itttq.com</a> Inc. All rights reserved. 
 */
package com.itttq.gshop.h5.controller.user;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.itttq.gshop.domain.po.UserInfoPo;
import com.itttq.gshop.domain.to.ResultTo;
import com.itttq.gshop.generic.cmpt.annotation.Auth;
import com.itttq.gshop.generic.connector.IOrderInfoConnector;
import com.itttq.gshop.generic.connector.IUserInfoConnector;
import com.itttq.gshop.generic.controller.GenericController;
import com.itttq.gshop.generic.util.Constants;

@Auth(excls={"exist", "logout", "regUser", "login", "forgetPwd"})
@RestController
@RequestMapping("user")
public class UserController extends GenericController {
	// 图片上传目录，
	@Value("${gshop.file.img.upload}")
	public String imgUploadPath;
	// 图片URL地址，http://img.xx.com
	@Value("${gshop.file.img.url}")
	public String imgUrlPath;

	private static final long serialVersionUID = 997162097056404387L;
	@Autowired
	private IUserInfoConnector userInfoConnector;
	@Autowired
	private IOrderInfoConnector orderInfoConnector;
	@InitBinder
	// 解决日前格式校验不通过的问题
	public void initBinder(WebDataBinder webDataBinder) {
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    dateFormat.setLenient(false);
	    webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	/**
	 * 个人首页
	 * @return
	 */
	@RequestMapping("index.html")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mv = editUserInfo(request);
		mv.setViewName("/mine/index");
		//TODO GXG 获取各种状态订单总数，在用户首页显示
		return mv;
	}
	
	/**
	 * 我的推广
	 * @return
	 */
	@RequestMapping("amb.html")
	public ModelAndView amb(HttpServletRequest request) {
		ModelAndView mv = editUserInfo(request);
		mv.setViewName("/mine/myAmb");
		return mv;
	}
	
	/**
	 * 我的推广人员
	 * @return
	 */
	@RequestMapping("members.html")
	public List<UserInfoPo> ambMembers(HttpServletRequest request) {
		UserInfoPo user = new UserInfoPo();
		user.setPromoterId(this.getUserIdFromSession(request));
		this.setPpt(request, user);
		return userInfoConnector.getUsers(user);
	}
	
	/**
	 * 跳转到编辑头像页面
	 * @param id
	 * @return
	 */
	@RequestMapping("head.html")
	public ModelAndView editHeader(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/mine/head");
		mv.addObject("user", this.getUserFromSession(request));
		return mv;
	}
	
	/**
	 * 跳转到编辑头像页面
	 * @param id
	 * @return
	 */
	@RequestMapping("saveHead.html")
	public ResultTo saveHead(String img, HttpServletRequest request) {
		img = img.replaceAll("data:image/jpeg;base64,", "");
		ResultTo rt = new ResultTo();
		try {
			// 获取当前图片上传路径
			UserInfoPo user = this.getUserFromSession(request);
			String filePath = Constants.SEPARATOR_BACKSLASH + Constants.UPLOAD_DIR.get(5)
					+ Constants.SEPARATOR_BACKSLASH +  Constants.getFilenameByTime("head") +".jpg";
			boolean rs = Constants.generateImage(img, imgUploadPath + filePath);
			if(rs == false) {
				rt.setCode(ResultTo.FAIL);
				return rt;
			}
			user.setHead(imgUrlPath + filePath);
			this.setSession(request, Constants.SESSION_USER, user);
			// 新建一个user对象，只把头像和用户ID赋值
			UserInfoPo u = new UserInfoPo();
			u.setId(user.getId());
			u.setHead(imgUrlPath + filePath);
			userInfoConnector.saveUserInfo(u);
		} catch (Exception e) {
			e.printStackTrace();
			rt.setCode(ResultTo.FAIL);
		}
		return rt;
	}
	
	/**
	 * 跳转到编辑页面
	 * @param id
	 * @return
	 */
	@RequestMapping("edit.html")
	public ModelAndView editUserInfo(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/mine/user-edit");
		mv.addObject("user", this.getUserFromSession(request));
		return mv;
	}
	
	/**
	 * 根据手机号判断用户是否存在
	 * @param mobile
	 * @return
	 */
	@RequestMapping("exist.html")
	public boolean exist(String mobile) {
		return userInfoConnector.exist(mobile);
	}
	
	/**
	 * 保存UserInfoPo对象，无ID则新增，有ID则更新
	 * 
	 * @param userInfo
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("info.html")
	public ModelAndView userInfo(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/mine/user");
		mv.addObject("user", this.getUserFromSession(request));
		return mv;
	}
	
	/**
	 * 保存UserInfoPo对象，无ID则新增，有ID则更新
	 * 
	 * @param userInfo
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("save.html")
	public ModelAndView saveUserInfo(UserInfoPo userInfo, HttpServletRequest request) {
		// 为避免修改其他人的信息
		userInfo.setId(this.getUserIdFromSession(request));
		userInfoConnector.saveUserInfo(userInfo);
		// 更新缓存
		this.setSession(request, Constants.SESSION_USER, userInfoConnector.getUserInfo(userInfo.getId()));
		return userInfo(request);
	}
	
	/**
	 * 忘记密码
	 * @return
	 */
	@RequestMapping("forgetPwd.html")
	public ModelAndView forgetPwd(UserInfoPo user, String vc, HttpServletRequest request) {
		return userOp(Constants.SESSION_CODE_GETPWD, user, vc, "forgetPwd", request);
	}
	
	/**
	 * 保存UserInfoPo对象，无ID则新增，有ID则更新
	 * 
	 * @param userInfo
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("reg.html")
	public ModelAndView regUser(UserInfoPo user, String vc, HttpServletRequest request) {
		return userOp(Constants.SESSION_CODE_REG, user, vc, "reg", request);
	}
	
	private ModelAndView userOp(String sessionKey, UserInfoPo user, String vc, String op,  HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/login");
		mv.addObject("user", user);
		mv.addObject("vc", vc);
		// 验证码验证 TODO GXG验证码半个小时过期
		Object obj = this.getSession(request, sessionKey + user.getMobile());
		if(null == obj || !obj.toString().equals(user.getMobile()+vc)) {
			mv.addObject("msg", "验证码错误");
			mv.addObject("op", op);
			return mv;
		}
		user.setIpRegister(Constants.getIp(request));
		int rs  = 0;
		if(sessionKey.equals(Constants.SESSION_CODE_REG)) {
			userInfoConnector.reg(user);
		} else if(sessionKey.equals(Constants.SESSION_CODE_GETPWD)) {
			userInfoConnector.updatePwdByMobile(user);
		}
		// TODO GXG 清空验证码
		// 注册成功，直接登录
		if(rs == 1) mv = login(user, request);
		return mv;
	}
	
	/**
	 * 根据手机号和密码登录
	 * 
	 * @param mobile	手机号
	 * @param pwd		密码
	 * @Author 迷蝶
	 * @return UserInfoPo	登录成功则返回登录用户对象，用户名密码错误则返回null
	 */
	@RequestMapping("login.html")
	public ModelAndView login(UserInfoPo user, HttpServletRequest request) {
		UserInfoPo userInfo = userInfoConnector.login(user.getMobile(), user.getPassword(), Constants.getIp(request));
		ModelAndView mv = new ModelAndView("/mine/index");
		if(null == userInfo) {
			mv.setViewName("/login");
			mv.addObject("msg", "用户名或密码错误！");
		} else {
			this.setSession(request, Constants.SESSION_USER, userInfo);
			// 如果有最后一次登录url记录，则跳转到最后一次登录地址
			Object obj = this.getSession(request, Constants.SESSION_URL_LAST);
			if(null != obj) {
				mv.setViewName("redirect:" + obj.toString());
			} else {
				mv.addObject("user", userInfo);
			}
		}
		return mv;
	}
	
	/**
	 * 退出登录
	 * 
	 * @Author 迷蝶
	 * @return 
	 */
	@RequestMapping("logout.html")
	public ModelAndView logout(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/login");
		this.getSession(request).invalidate();
		return mv;
	}
}